package servlet;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-03-11
 * Time:10:28
 */
//这个类不是servlet，而是一个监听器
//    通过这个来捕获到ServletCONTEXT 被 tomcat 创建好的这个动作
    @WebListener//通过这个注解Tomcat才能认识这是一个监听器对象
public class ThymeleafListener implements ServletContextListener {
//        被创建是使用
//    在下面这个代码中初始化Thymeleaf
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        TemplateEngine engine = new TemplateEngine();
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContextEvent.getServletContext());
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf8");
        engine.setTemplateResolver(resolver);
        //把创建好的engine放到ServletContext里面.
//        类似的操作在HttpSession这里也用到过
        servletContextEvent.getServletContext().setAttribute("engine",engine );
        System.out.println("thymeleaf初始化完毕");
    }
//      被销毁前使用
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
